import React, { memo, useEffect, useState, useRef } from "react";
import { useSelector, shallowEqual } from "react-redux";
import { Moodwrap } from "./style";
import request from "@/service/request";
import { ymd } from "@/utils/timeutil";
import qs from "qs";
export default memo(function Mood() {
  const moodref = useRef();
  const [moodlist, setMoodlist] = useState([]);

  const { user } = useSelector(
    (store) => ({
      user: store.userstore.user,
    }),
    shallowEqual
  );
  useEffect(() => {
    console.log(user.id);
    request
      .get(`travel/Getmood?id=${user.id}`)
      .then((res) => {
        setMoodlist(res);
      })
      .catch((err) => {
        console.log("获取心情说说接口出错");
      });
  }, [user]);
  //添加心情
  const addmood = () => {
    const values = {
      content: moodref.current.value,
      bloggerid: user.id,
      date: ymd(),
    };
    request.post("travel/Getmood", qs.stringify(values)).then((value) => {
      request.get(`travel/Getmood?id=${user.id}`).then((res) => {
        setMoodlist(res);
        moodref.current.value = "";
      });
    });
  };
  return (
    <Moodwrap>
      <div className="content1">
        {moodlist.length > 0 ? (
          moodlist.map((item, index) => {
            return (
              <div className="item" key={index}>
                {(index === 0 ||
                  item.date.slice(0, 4) !==
                    moodlist[index - 1].date.slice(0, 4)) && (
                  <div className="year">{item.date.slice(0, 4)}</div>
                )}
                <div className="main">
                  <div className="left">
                    <span className="yearfont">{item.date}</span>
                  </div>
                  <div className="middle"></div>
                  <div className="right">{item.content}</div>
                </div>
              </div>
            );
          })
        ) : (
          <div className="nowrap">
            <img
              src="https://mp-blog.csdn.net/mp_blog/img/monkey-blank.137fa3ce.png"
              alt=""
            />
            <div className="tooltip">空空如也，留下你的痕迹吧</div>
          </div>
        )}
      </div>
      <div className="pubmood">
        <input ref={moodref} className="ii" placeholder="留下你今天的心情" />
        <div className="san"></div>
        <img src={user.aventer} alt="" />
        <button onClick={addmood}>确定</button>
      </div>
    </Moodwrap>
  );
});
